/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package main.grid;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import main.environment.DefaultEnvironmentImpl;
import main.environment.IEnvironment;
import main.environment.LevelChange;
import main.environment.loader.EnvironmentLoader;
import main.rendering.Panel;

/**
 *
 * @author Fox
 */
public class Core implements ActionListener{
    private Timer timer;    
    private Screen screen;
    private Panel panel;
    private IEnvironment environment;
    private EnvironmentLoader el;
    
    public Core(){
        environment = new DefaultEnvironmentImpl();
        panel = new Panel(environment);
        screen = new Screen(panel);
        panel.addKeyListener(new TAdapter());
        
        try {
            el = new EnvironmentLoader(
                    environment,
                    ImageIO.read(new File("./media/environment/serv.bmp")),
                    ImageIO.read(new File("./media/environment/servFloor.bmp")));
        } catch (IOException ex) {
            Logger.getLogger(Core.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        el.changeLevel(new LevelChange(17,9));
        
        timer = new Timer(25, this);
        timer.start();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        environment.run();   
        
        LevelChange lc = environment.getEntityHandler().getEntity(0).getLocation().getChange();
        if (lc != null) {
            el.changeLevel(lc);
        }     
        
        panel.repaint();  
    }
    
    
    private class TAdapter extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case (KeyEvent.VK_LEFT): 
                    environment.getEntityHandler().getEntity(0).getVector().x=-1;
                    break;
                case (KeyEvent.VK_RIGHT): 
                    environment.getEntityHandler().getEntity(0).getVector().x=1;
                    break;
                case (KeyEvent.VK_UP): 
                    environment.getEntityHandler().getEntity(0).getVector().y=-1;
                    break;
                case (KeyEvent.VK_DOWN): 
                    environment.getEntityHandler().getEntity(0).getVector().y=1;
                    break;
                } 
        }
        
        public void keyReleased( KeyEvent e) {
            //
        }
    }
}
